<template>
  <el-drawer
    v-model="visible"
    :title="documentName"
    direction="rtl"
    size="60%"
    :before-close="handleClose"
    destroy-on-close
  >
    <div class="h-full flex flex-col bg-gray-50 dark:bg-gray-900">
      <!-- 图谱内容 -->
      <div class="flex-1 flex flex-col overflow-hidden">
        <!-- 图谱容器 -->
        <div class="flex-1 bg-white dark:bg-gray-800 relative overflow-hidden">
          <knowledge-graph-component
            :data="graphData"
            :loading="loading"
            class="w-full h-full"
          />
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import { getKnowledgeGraph } from '/@/api/knowledge/aiDocument';
import KnowledgeGraphComponent from './KnowledgeGraphComponent.vue';
import { createSampleData, type GraphData, type GraphNode, type GraphLink } from './simpleData';

// 接口定义已从 simpleData.ts 导入

const props = defineProps<{
  modelValue: boolean;
  documentId?: string;
  documentName?: string;
}>();

const emit = defineEmits<{
  'update:modelValue': [value: boolean];
}>();

const { t } = useI18n();

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});

const loading = ref(false);
const error = ref('');
const graphData = ref<GraphData | null>(null);

const handleClose = () => {
  visible.value = false;
};

// 是否使用Mock数据
const useGraphMock = import.meta.env.VITE_GRAPH_MOCK === 'true';

const loadGraphData = async () => {
  if (!props.documentId) {
    error.value = t('knowledgeGraph.invalidDocumentId');
    return;
  }
  
  loading.value = true;
  error.value = '';
  graphData.value = null;
  
  try {
    if(useGraphMock){
      graphData.value = createSampleData();
      return;
    }

    const { data } = await getKnowledgeGraph(props.documentId);

    // 处理后端返回的数据，转换为 D3 可用的格式
    if (data?.nodes && data?.links) {
      graphData.value = {
        nodes: data.nodes.map((node: any) => ({
          id: node.id || node.identity?.toString() || Math.random().toString(),
          labels: node.labels || [],
          properties: node.properties || {}
        })),
        links: data.links.map((link: any) => ({
          source: link.source || link.start?.toString(),
          target: link.target || link.end?.toString(),
          type: link.type || link.relationship || 'RELATED',
          properties: link.properties || {}
        }))
      };
    } else {
      graphData.value = createSampleData();
    }
  } catch (err: any) {
    error.value = err.message || t('knowledgeGraph.loadFailure');
    useMessage().error(t('knowledgeGraph.loadFailure'));
  } finally {
    loading.value = false;
  }
};


// 监听抽屉打开状态，自动加载数据
watch(() => props.modelValue, (newValue) => {
  if (newValue && props.documentId) {
    // 延迟加载，确保抽屉完全打开后再初始化图谱
    setTimeout(() => {
      loadGraphData();
    }, 300);
  }
});

// 监听文档ID变化
watch(() => props.documentId, (newDocumentId) => {
  if (newDocumentId && props.modelValue) {
    setTimeout(() => {
      loadGraphData();
    }, 300);
  }
});
</script>
